//
//  FunctionsAndClosures.swift
//  a_swift_tour
//
//  Created by yao_yu on 14-8-18.
//  Copyright (c) 2014年 yao_yu. All rights reserved.
//

import Foundation


// P19 函数和闭包
func FunctionsAndClosures(){
    //P19
    func greet(name:String, day:String) -> String{
        return "Hello \(name), today is \(day)"
    }
    //println(greet("Bob", "Tuesday"))
    
    // P20
    func calculateStatistics(scores:[Int]) ->(min:Int, max:Int, sum:Int){
        var min = scores[0]
        var max = scores[0]
        var sum = 0
        for score in scores{
            if score > max{
                max = score
            } else if score < min{
                min = score
            }
            sum += score
        }
        return (min, max, sum)
    }
    let statistics = calculateStatistics([5, 3, 100, 3, 9])
    // println("\(statistics.sum), \(statistics.1)")
    
    // P21 变参
    func sumOf(numbers:Int...) -> Int{
        var sum = 0
        for number in numbers{
            sum += number
        }
        return sum
    }
    // println("\(sumOf()), \(sumOf(1, 2, 3))")
    
    func averageOf(numbers: Int...) -> Int{
        var a = 0
        for i in numbers{
            a += i
        }
        return a / numbers.count
    }
    // println(averageOf(2,2,3))
    
    // P22 嵌套函数
    func returnFifteen() -> Int{
        var y = 10
        func add(){
            return y += 5
        }
        add()
        return y
    }
    // println(returnFifteen())
    
    // 返回函数
    func makeIncrementer() -> (Int -> Int){
        func addOne(number: Int) -> Int{
            return 1 + number
        }
        return addOne
    }
    var increment = makeIncrementer()
    // println(increment(7))
    
    // P23 函数作为参数
    func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool{
        for item in list{
            if condition(item){
                return true
            }
        }
        return false
    }
    func lessThanTen(number:Int)->Bool{
        return number < 10
    }
    var numbers = [20, 29, 7, 12]
    //println(hasAnyMatches(numbers, lessThanTen))
    
    // 函数其实是一类特殊的闭包: 一段在后面执行的代码
    var b = numbers.map({
        (number:Int)->Int in
        if (number % 2) == 0{
            return 0
        }
        return number
    })
    b = numbers.map{
        if $0 % 2 == 1{
            return 0
        }
        return $0
    }
    //println(b)
}
